/**
 * Name:        StringUtil.java  
 * Description: 
 * @author      martin
 * @version     0.1
 *
 **************************************************************
 * Created on 2005-11-2  21:44:39
 **************************************************************
 * Modify History:
 *
 */
package com.wy.component.dataConvert;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.CharacterIterator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil {
	private static final String NUMBER_PATTERN = "^[0-9]+(.[0-9]{0,2})?$";

	public static String concatStrForSql(String str) {
		String result = "";
			str = str.replace(" ", "");
			String arr[] = str.split(",");
			for (int i = 0; i < arr.length; i++) {
				result += ",'" + arr[i] + "'";
			}
		return result.substring(1);
	}
	
    public static String getAgeByIdCode(String str) {
    	if (str == null || (str.length() != 15 && str.length() != 18)) {
			return "";
		}
		String yy1 = str.substring(6, 10);// 出身的年份
		String mm1 = str.substring(10, 12);// 出身的月份
		String dd1 = str.substring(12, 14);// 出身的日份
		String birthday = yy1.concat("-").concat(mm1).concat("-").concat(dd1);
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String s1 = sdf.format(date);
		Date today = null;
		Date birth = null;
		try {
			today = sdf.parse(s1);
			birth = sdf.parse(birthday);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		int age = today.getYear() - birth.getYear();
		return String.valueOf(age);
	}

	public static String getSexByIdCode(String value) {
		value = value.trim();
		
		if (value == null || (value.length() != 15 && value.length() != 18)) {
			return "";
		}
		if (value.length() == 15 || value.length() == 18) {
			String lastValue = value.substring(value.length() - 1,
					value.length());
			
			int sex;
			if (lastValue.trim().toLowerCase().equals("x")
					|| lastValue.trim().toLowerCase().equals("e")) {
				return "1";
			} else {
				String v = value.substring(value.length() - 2,
						value.length()-1);
				sex = (Integer.parseInt(v)) % 2;
				return sex == 0 ? "0" : "1";
			}
		} else {
			return "";
		}
	}
	
	public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
 
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else
            return String.format("%d B", size);
    }
	
	public static String replace(String queryStr, String oldstr,
			String replacement) {
		if (queryStr == null || oldstr == null) {
			return queryStr;
		}
		int lengthqueryStr = queryStr.length();
		int lengtholdstr = oldstr.length();
		int pos = queryStr.indexOf(oldstr);
		int beginIndex = 0;
		List strlist = new ArrayList(4);

		while (beginIndex < lengthqueryStr) {
			if (pos == -1)
				break;
			strlist.add(queryStr.substring(beginIndex, pos));
			beginIndex = pos + lengtholdstr;
			pos = queryStr.indexOf(oldstr, beginIndex);
		}
		strlist.add(queryStr.substring(beginIndex));
		StringBuffer sb = new StringBuffer("");
		for (int i = 0; i < strlist.size() - 1; i++) {
			sb.append(strlist.get(i)).append(replacement);
		}
		sb.append(strlist.get(strlist.size() - 1));
		return sb.toString();
	}

	public static String hidePass(String password) {
		return encrypt(password);
	}

	public static String showPass(String password) {
		return encrypt(password);
	}

	private static String encrypt(String pass) {
		char[] orig = pass.toCharArray();
		byte[] dest = new byte[orig.length];
		for (int i = 0; i < orig.length; i++)
			dest[i] = (byte) (orig[i] ^ (0x10 + i));
		return new String(dest);
	}

	public static String getUTF8String(String src) {
		try {
			return new String(src.getBytes("ISO8859_1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return src;
		}
	}

	public static String getISOString(String src) {
		try {
			return new String(src.getBytes("UTF-8"), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return src;
		}
	}

	public static java.util.List conv2List(String value, String delim) {

		java.util.List stringList = new ArrayList();
		StringTokenizer parser = new StringTokenizer(value, delim);
		while (parser.hasMoreTokens()) {
			stringList.add(parser.nextToken());
		} // end of while
		return stringList;
	}

	public static java.util.List conv2List(String value) {
		return conv2List(value, "#");
	}

	public static Date string2Date(String str) {
		return DateUtil.getDate(str, "yyyy-MM-dd");
	}

	public static Date string2Datetime(String str) {
		return DateUtil.getDate(str, "yyyy-MM-dd HH:mm:ss");
	}

	public static Date string2Time(String str) {
		return DateUtil.getDate(str, "HH:mm:ss");
	}

	/**
	 * 将yyyymmdd格式的日期转换为yyyy-mm-dd
	 * 
	 * @param date
	 * @return String
	 * @author 马霖
	 */
	public static String date8to10(String date) {
		if (date == null || date.trim().length() == 0)
			return "";
		else if (date.trim().length() == 8)
			return date.substring(0, 4) + "-" + date.substring(4, 6) + "-"
					+ date.substring(6, 8);
		else
			return date;
	}

	/**
	 * 将yyyy-mm-dd格式的日期转换为yyyymmdd
	 * 
	 * @param date
	 * @return String
	 * @author 马霖
	 */
	public static String date10to8(String date) {
		if (date == null || date.trim().length() == 0)
			return "";
		else if (date.trim().length() == 10)
			return date.substring(0, 4) + date.substring(5, 7)
					+ date.substring(8, 10);
		else
			return date;
	}

	/**
	 * 返回6位字符串,数字不足前面补0
	 * 
	 * @param i
	 *            -- 负数时,返回"00000",超过6位时,返回原字符串
	 * @return
	 */
	public static String get6bitString(int i) {
		return getbitString(i, 1);
	}

	/**
	 * 返回5位字符串,数字不足前面补0
	 * 
	 * @param i
	 *            -- 负数时,返回"0000",超过5位时,返回原字符串
	 * @return
	 */
	public static String get5bitString(int i) {
		return getbitString(i, 2);
	}

	private static String getbitString(int i, int type) {
		String str = "";
		switch (type) {
		case 1:
			str = "00000";
			break;
		case 2:
			str = "0000";
			break;
		default:
			;
		}
		if (i >= 0) {
			int j = i;
			while (j > 9) {
				j = j / 10;
				if ("".equals(str))
					break;
				str = str.substring(0, str.length() - 1);
			}
			str += String.valueOf(i);
		}
		return str;
	}

	/**
	 * 将输入的字符串转换为UTF8字符串
	 * 
	 * @param s
	 *            -- 输入的字符串
	 * @return 转换后的字符串
	 */
	public static String toUTF8String(String s) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c >= 0 && c <= 255) {
				sb.append(c);
			} else {
				byte[] b;
				try {
					b = Character.toString(c).getBytes("utf-8");
				} catch (Exception ex) {
					System.out.println(ex);
					b = new byte[0];
				}
				for (int j = 0; j < b.length; j++) {
					int k = b[j];
					if (k < 0)
						k += 256;
					sb.append("%" + Integer.toHexString(k).toUpperCase());
				}
			}
		}
		return sb.toString();
	}

	/*
	 * 四舍五入方法返回值为String无效返回值为 -100
	 */
	public static double getValueForDb(String v, int scale) {
		try {
			double dv = Double.parseDouble(v) / 100;
			BigDecimal b = new BigDecimal(dv);
			BigDecimal one = new BigDecimal("1");
			return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
		} catch (Exception e1) {
			System.err.println(e1.getMessage());
			return -100;
		}
	}

	// 完整转译
	public static String FullHTMLEncode(String aTagFragment) {
		if (aTagFragment == null) {
			return "";
		}
		final StringBuffer result = new StringBuffer();
		final StringCharacterIterator iterator = new StringCharacterIterator(
				aTagFragment);
		char character = iterator.current();
		while (character != CharacterIterator.DONE) {
			if (character == '<') {
				result.append("&lt;");
			} else if (character == '>') {
				result.append("&gt;");
			} else if (character == '\"') {
				result.append("&quot;");
			} else if (character == '\'') {
				result.append("&#039;");
			} else if (character == '\\') {
				result.append("&#092;");
			} else if (character == '&') {
				result.append("&amp;");
			} else {
				result.append(character);
			}
			character = iterator.next();
		}
		return result.toString();
	}

	public static boolean haveHTMLcode(String aTagFragment) {
		if (aTagFragment == null) {
			return false;
		}
		final StringCharacterIterator iterator = new StringCharacterIterator(
				aTagFragment);
		char character = iterator.current();
		while (character != CharacterIterator.DONE) {
			if (character == '<') {
				return true;
			} else if (character == '>') {
				return true;
			} else if (character == '\"') {
				return true;
			} else if (character == '\'') {
				return true;
			} else if (character == '\\') {
				return true;
			} else if (character == '&') {
				return true;
			}
			character = iterator.next();
		}
		return false;
	}

	public static boolean haveDownHTMLcode(String aTagFragment) {
		if (aTagFragment == null) {
			return false;
		}
		final StringCharacterIterator iterator = new StringCharacterIterator(
				aTagFragment);
		char character = iterator.current();
		while (character != CharacterIterator.DONE) {
			if (character == '/') {
				return true;
			}
			character = iterator.next();
		}
		return false;
	}

	/**
	 * 把为空字段转化成页面的空格&nbsp;
	 */
	public static String convertNbsp(String str) {
		if (str == null || str.trim().length() == 0
				|| str.trim().equals("null")) {
			str = " ";
		}
		return str;
	}

	/**
	 * 把为空字段转化成页面的空格&nbsp;
	 */
	public static String convertNull(String str) {
		if (str == null || str.trim().length() == 0
				|| str.trim().equals("null")) {
			str = "";
		}
		return str;
	}


	/**
	 * 
	 * Function Name match
	 * 
	 * @param pattern
	 *            表达式
	 * @param str
	 *            待验证字符串
	 * @return boolean
	 * @description 执行正则表达式
	 */
	private static boolean match(String pattern, String str) {
		Pattern p = Pattern.compile(pattern);
		Matcher m = p.matcher(str);
		return m.find();
	}

	/**
	 * Function Name isDecimalNumber
	 * 
	 * @param 输入数值参数
	 * @return boolean
	 * @description 判断是否为数值类型，长度符合数据库Number(18,2)类型 Modification History
	 *              //修改历史说明
	 */
	public static boolean isDecimalNumber(String number) {
		boolean length = false;
		boolean match = false;
		int index = number.indexOf(".");
		if ((index != -1 && number.substring(0, index).length() <= 13)
				|| (index == -1 && number.length() <= 15)) {//判断整型部分长度
			length = true;
		}
		match = match(NUMBER_PATTERN, number);
		if (length && match) {
			return true;
		} else {
			return false;
		}
	}
}
